﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace zielonka.co.uk.extensions.system.io
{
    // Description:	Copies a stream to another stream using a passed buffer. it also has an overload to pass a buffer length.
    /*
        Stream fSource=File.OpenRead(@"C:\test.bin");
        Stream fDest=File.Create(@"C:\CopyOfTest.bin");
        fSource.CopyTo(fDest,10*1024);
     */

    public static partial class StreamExtensions
    {/// <summary>
        /// Copies an stream to another stream using the buffer passed.
        /// </summary>
        /// <param name="source">source stream</param>
        /// <param name="destination">destination stream</param>
        /// <param name="buffer">buffer to use during copy</param>
        /// <returns>number of bytes copied</returns>
        public static long CopyTo(this Stream source, Stream destination, byte[] buffer)
        {
            long total = 0;
            int bytesRead;
            while (true)
            {
                bytesRead = source.Read(buffer, 0, buffer.Length);
                if (bytesRead == 0)
                    return total;
                total += bytesRead;
                destination.Write(buffer, 0, bytesRead);
            }
        }
        /// <summary>
        /// Copies an stream to another stream using the buffer with specified size.
        /// </summary>
        /// <param name="source">source stream</param>
        /// <param name="destination">destination stream</param>
        /// <param name="bufferLen">length of buffer to create</param>
        /// <returns>number of bytes copied</returns>
        public static long CopyTo(this Stream source, Stream destination, int bufferLen)
        {
            return source.CopyTo(destination, new byte[bufferLen]);
        }
    }
}
